<template>
    <div class="e-form">
        <BillTop  @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs">
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
            >
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="调拨明细"
                    name="detailed"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="附件信息"
                    name="attach"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="审核历史"
                    name="auditHistory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>

                <div>
                    <div id="baseInfoCon" class="con">

                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                                <el-form :model="basicForm" :label-width="formLabelWidth"
                                ref="ruleForm"
                             :rules="rules"
                             class="demo-ruleForm"
                                >
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="变更编号：">
                                    <span>{{ basicForm.billNo	 }}</span>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                               <el-form-item label="调动编号：">
                                    <span>{{ basicForm.parentNo }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="变更日期：">
                                    <el-date-picker
                                        value-format="yyyy-MM-dd"
                                        type="date"
                                        placeholder="选择日期"
                                        v-model="basicForm.changedDate"
                                    ></el-date-picker>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                               <el-form-item label="机构：">
                                    <span>{{ basicForm.orgName }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="调入机构：">
                                    <span>
                                        {{
                                            basicForm.transferInOrgName
                                        }}
                                    </span>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                               <el-form-item label="接收人员：">
                                     <span>
                                        {{
                                            basicForm.receiverName
                                        }}
                                    </span>

                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row>

                             <el-col :span="12">
                                 <el-form-item label="原税价合计（元）：" >
                                   <span>
                                       {{basicForm.baseCurNotTaxprice}}
                                   </span>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">

                                    <el-form-item label="经办人员：">
                                 <span>
                                       {{basicForm.operatorName}}

                                   </span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                 <el-form-item label="税率%：" prop="taxRate" >
                                  <el-input
                                                @input="onTaxRate"
                                                v-enter-integer2="{
                                                set: this,
                                                val: 'basicForm',
                                                key: 'taxRate'
                                                }"
                                                v-model="basicForm.taxRate"
                                            ></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">

                                    <el-form-item label="税额：" prop="taxAmount">
                                            <el-input
                                            @input="onTaxRate('taxAmount')"
                                            v-enter-float="{
                                            set:this,
                                            val:'basicForm',
                                            key:'taxAmount'
                                            }"
                                            v-model="basicForm.taxAmount"
                                            ></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                          <el-row>
                           <el-col :span="12">
                                 <el-form-item label="不含税租赁金额（元）：">
                                   <span>
                                       {{basicForm.rmbNotTaxprice}}
                                   </span>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">

                                    <el-form-item label="状态：">
                                  <span>{{ statusLable(basicForm.state)}}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                         <el-row>
                            <el-col :span="12">
                                <el-form-item label="变更后税价合计（元）：">
                                    <span>{{ basicForm.changedTotalMoney }}</span>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="人民币汇率：">
                                    <span>{{
                                        basicForm.rmbRate
                                    }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="币种：">

                                    <span>
                                        {{
                                            basicForm.currency
                                        }}
                                    </span>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="变更期数：">
                                    <span>{{ basicForm.period }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>

                           <el-row>
                            <el-col :span="24">
                                <el-form-item label="备注：">
                                    <el-input
                                        type="textarea"
                                        v-model="basicForm.remarks"
                                        autocomplete="off"
                                    ></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="本位币：">
                                    <span>{{ basicForm.baseCurName }}</span>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="本位币汇率：">
                                    <span>{{
                                        basicForm.baseCurRate
                                    }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                        </div>
                    </div>
                    <!-- 物资明细 -->
                    <div id="detailedCon" class="con">
                        <div class="tabs-title" id="detailed">闲置明细</div>
                        <div class="e-table">
                            <div class="top">
                                <div class="left">
                                    <el-button size="mini" type="primary"
                                        class="btn-greenYellow"
                                        @click="selectIdle"
                                        >周材闲置</el-button
                                    >
                                </div>
                            </div>
                          <div class="errorMsg" v-if="errorMsg.length > 0">
                                <span
                                    v-for="(item, index) in errorMsg"
                                    :key="index"
                                >
                                    {{ item }}
                                </span>
                            </div>
                           <el-table
                                class="table"
                                :data="detailedTableData"
                                border
                                style="width: 100%"
                                 default-expand-all
                                :header-cell-style="{ textAlign: 'center' }"
                                :cell-style="{ textAlign: 'center' }"
                                :tree-props="{
                                    children: 'children',
                                    hasChildren: 'hasChildren'
                                }"
                                ref="multipleTable"
                                row-key="uuid"
                                 :row-class-name="tableRowClass"
                                 v-sortTable="{ 'tableData': detailedTableData, '_this': this, 'ref': 'multipleTable' }"
                            >
                                <el-table-column
                                    label="操作"
                                    fixed
                                    width="100px"
                                    align="left"
                                >

                                    <template slot-scope="{ row, $index }">

                                        <i
                                            class="el-icon-delete"
                                            style="
                                                cursor: pointer;
                                                font-size: 20px;
                                                color: red;
                                            "
                                            :class="{
                                                'icon-delete-active-color':
                                                    MouseEnterId == row.dtlId
                                            }"
                                            @click="deleteEle(row)"
                                            v-if="$index > 0"
                                        ></i>

                                    </template>

                                </el-table-column>
                                <el-table-column
                                    prop="materialClassName"
                                    label="类别"
                                    mini-width="300"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="materialName"
                                    label="物资名称"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="spec"
                                    label="规格"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="unit"
                                    label="计量单位"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="texture"
                                    label="材质"
                                    width="200"
                                >

                                </el-table-column>
                                       <el-table-column
                                    prop="quantity"
                                    label="数量"
                                    width="100"
                                >
                                </el-table-column>
                                   <el-table-column
                                    prop="quantity"
                                    label="租赁数量"
                                    width="200"
                                >
                                </el-table-column>

                                <el-table-column
                                    width="200"
                                >
                                 <template slot="header">
                                     <div class="tab-header">
                                            租赁数量<span class="tab-heade-icon"
                                                >变</span
                                            >
                                        </div>
                                </template>
                                 <template slot-scope="{ row, $index }">
                                        <el-input
                                            @input="curStateChange(row)"
                                             v-enter-integer1="{
                                            set: row,
                                            key: 'quantityChanged'
                                             }"
                                            v-model="row.quantityChanged"
                                            clearable
                                            v-if="$index > 0"
                                        ></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="degree"
                                    label="新旧程度%"
                                    width="200"
                                >
                                  <template slot="header">
                                     <div class="tab-header">
                                            新旧程度<span class="tab-heade-icon"
                                                >变</span
                                            >
                                        </div>
                                </template>
                                 <template slot-scope="{ row, $index }">
                                        <el-input
                                             v-enter-integer1="{
                                            set: row,
                                            key: 'degreeChanged'
                                             }"
                                            @input="curStateChange(row)"

                                            v-model="row.degreeChanged"
                                            clearable
                                            v-if="$index > 0"
                                        ></el-input>
                                    </template>
                                </el-table-column>
                                  <el-table-column
                                    prop="price"
                                    label="租赁单价（元）"
                                    width="200"
                                >
                                </el-table-column>

                                <el-table-column

                                    width="200"
                                >
                                 <template slot="header">
                                     <div class="tab-header">
                                            租赁单价（元）<span class="tab-heade-icon"
                                                >变</span
                                            >
                                        </div>
                                </template>
                                     <template slot-scope="{ row, $index }">
                                        <el-input
                                              v-enter-float="{
                                            set: row,
                                            key: 'priceChanged'
                                        }"
                                            @input="curStateChange(row)"

                                            v-model="row.priceChanged"
                                            clearable
                                            v-if="$index > 0"
                                        ></el-input>
                                    </template>
                                </el-table-column>
                                  <el-table-column

                                    prop="timeUnit"
                                    label="计时单位"
                                    width="200"
                                >

                                </el-table-column>
                                <el-table-column
                                    width="200"
                                >
                                  <template slot="header">
                                     <div class="tab-header">
                                            计时单位<span class="tab-heade-icon"
                                                >变</span
                                            >
                                        </div>
                                </template>
                                 <template slot-scope="{ row, $index }">
                                        <el-select
                                            v-model="row.timeUnitChanged"
                                            placeholder="请选择"
                                            @input="curStateChange(row)"
                                            v-if="$index > 0"
                                        >
                                            <el-option
                                                v-for="item in timeUnitList"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.label"
                                            >
                                            </el-option>
                                        </el-select>
                                    </template>
                                </el-table-column>
                                    <el-table-column

                                    prop="useTime"
                                    label="预计使用时间"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column

                                    prop="useTimeChanged"
                                    label="预计使用时间"
                                    width="200"
                                >
                                 <template slot="header">
                                     <div class="tab-header">
                                            预计使用时间<span class="tab-heade-icon"
                                                >变</span
                                            >
                                        </div>
                                </template>
                                <template slot-scope="{row, $index }">
                                    <el-input
                                      v-enter-float="{
                                            set: row,
                                            key: 'useTimeChanged'
                                        }"
                                    v-model="row.useTimeChanged" @input="curStateChange(row)"

                                            v-if="$index > 0"

                                    ></el-input>
                                </template>
                                </el-table-column>
                                 <el-table-column

                                    prop="cost"
                                    label="预计进场费用"
                                    width="200"
                                >
                                 </el-table-column>
                                <el-table-column

                                    prop="costChanged"
                                    label="预计进场费用"
                                    width="200"
                                >
                                 <template slot="header">
                                     <div class="tab-header">
                                            预计进场费用<span class="tab-heade-icon"
                                                >变</span
                                            >
                                        </div>
                                </template>
                                <template slot-scope="{row, $index }">
                                    <el-input
                                        v-enter-float="{
                                            set: row,
                                            key: 'costChanged'
                                        }"
                                    v-model="row.costChanged" @input="curStateChange(row)"

                                            v-if="$index > 0"

                                    ></el-input>
                                </template>
                                </el-table-column>
                                 <el-table-column
                                    prop="amount"
                                    label="金额（元）"
                                    width="200"
                                >

                                </el-table-column>
                            <el-table-column
                                    width="200"
                                >
                                 <template slot="header">
                                     <div class="tab-header">
                                            金额（元）<span class="tab-heade-icon"
                                                >变</span
                                            >
                                        </div>
                                </template>
                                <template slot-scope="{row,$index}">
                                    <span v-if="$index>0">
                                        {{
                                            row.amountChanged
                                        }}
                                    </span>
                                </template>
                                </el-table-column>

                            </el-table>
                        </div>
                    </div>
                    <!-- 附件信息 -->
                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">照片信息</div>
                    <attach-comp :relationId="attachId" bucketName="turnover" />

                    </div>
                     <!-- 审核历史 -->
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                            <ComAuditHistoryIndex
                                :billType="6073"
                                ref="AuditHistoryRef"
                            />
                        </div>
                    </div>

                </div>
            </el-tabs>
        </div>
        <div class="buttons">
          <ComExaButtons :auditState="auditState" :state="basicForm.state" @exas="exas" :founderId="basicForm.founderId" />
            <el-button size="small" @click="handleClose">关闭</el-button>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
    </div>
</template>

<script>
import auditRequest from '@/api/turnover/audit.js'
import ComAuditHistoryIndex from '@/pages/revolveMaterialManage/components/auditHistory/auditHistoryIndex'

import AttachComp from '@/components/common/attachIndex'
import { mapMutations, mapState } from 'vuex'
import otherRequest from '@/api/turnover/other.js'
import { getUuid, showLoading, hideLoading  } from '@/utils/common'
// import { doChildren } from '@/api/turnover/utils.js'
import { setInternalLeaseselectIdleRegistration } from '@/api/turnover/ppw.js'
import ComExaButtons from '@/components/common/exaButtons'
import { exas, saveAll, submitCommit } from '@/pages/revolveMaterialManage/common/revolveCom.js'
import $ from 'jquery'
import '@/utils/jquery.scrollTo.min'
export default {
    components: {
        ComAuditHistoryIndex, AttachComp, ComExaButtons
    },
    computed: {
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.billId
        },
        ...mapState({
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm, //币种
            timeUnitList: state => state.equip.equipData.timeUnitList //计时单位
        }),
        statusLable () {
            return param => {
                const state = this.$store.state.equip.equipData.state
                const obj = state.find(x => x.value === param)
                if (obj !== undefined) {
                    return obj.label
                }
            }
        },

    },
    watch: {
        //给错误标签加上提醒
        errorList: newData=>{
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM=>{
                const { childNodes } = DOM
                if(childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item=>{
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
    },
    mounted () {
        this.getLastConHeight()
        // 保存所有tabName
        const arr = ['baseInfo', 'detailed', 'attach', 'auditHistory']
        this.tabArr = arr  //标星星

        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if ((scrollTop + 1) >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
    },
    created () {
        this.billId = this.$route.query.billid
        this.getCurrentUnitInfo()
        this.getBasicInfo()
        this.getdtlList()
        this.getDicValue()
    },
    data () {
        return {
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            basicForm: {
                'baseCurId': '',
                'baseCurName': '',
                'baseCurNotTaxprice': 0,
                'baseCurRate': 0,
                'billId': '',
                'billNo': '',
                'changedDate': '',
                'changedDtlList': [
                    {
                        'amount': 0,
                        'amountChange': 0,
                        'billId': '',
                        'changeType': 0,
                        'cost': 0,
                        'costChange': 0,
                        'degreeChange': 0,
                        'dtlId': '',
                        'internalLeaseTransferDtlId': '',
                        'materialClassId': '',
                        'materialClassName': '',
                        'materialId': '',
                        'materialName': '',
                        'oldState': 0,
                        'price': 0,
                        'priceChange': 0,
                        'quantity': 0,
                        'quantityChange': 0,
                        'spec': '',
                        'texture': '',
                        'timeUnit': '',
                        'timeUnitChange': '',
                        'unit': '',
                        'useTime': 0,
                        'useTimeChange': 0
                    }
                ],
                'changedTotalMoney': 0,
                'currency': '',
                'currency_id': '',
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': '',
                'operatorId': '',
                'operatorName': '',
                'orgId': '',
                'orgName': '',
                'parentId': '',
                'parentNo': '',
                'period': 0,
                'receiverId': '',
                'receiverName': '',
                'remarks': '',
                'rmbId': '',
                'rmbName': '',
                'rmbNotTaxprice': 0,
                'rmbRate': 0,
                'state': 0,
                'taxAmount': 0,
                'taxRate': 0,
                'totalMoney': 0,
                'transferInOrgId': '',
                'transferInOrgName': '',
                'workId': ''
            },
            query: {
                limit: 10,
                number: '',
                orgname: '',
                page: 1,
                states: [],
            },
            auditState: {},

            rules: {
                taxAmount: [
                    {
                        required: true,
                        message: '税额',
                        trigger: 'blur'
                    }
                ],
                taxRate: [
                    {
                        required: true,
                        message: '税率',
                        trigger: 'blur'
                    }
                ],
            },
            auditParams: {
                billId: this.$route.query.billid,
                billType: 6073,
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: ''
            },
            formLabelWidth: '150px',
            detailedTableData: [], //物资明细
            changeTableData: [], //变更信息
            basicInfo: {},
            stateArr: ['草稿', '审核中', '已审核', '已作废'],
            MouseEnterId: 0,
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [],
            isErrorMsg: true, //是否提醒错误信息
        }
    },
    methods: {
        ...mapMutations(['setAuditParams']),

        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight = document.getElementById('recodesCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        getCurrentUnitInfo () {
            auditRequest.getCurrentUnitInfo(this.auditParams).then(res => {
                this.auditState = res
            })
        },
        getDicValue () {
            this.$store.dispatch('equip/setTimeUnitList')
        },
        // 获取明细
        getdtlList () {
            otherRequest.turnoverInternalLeaseTransferChangedGetDtlList(this.billId).then(res=>{
                console.log(res, 'res')
                if(res) {
                    res.forEach(item=>{
                        const count = item.children.reduce(
                            (prev, c) => (prev += c.amount || 0),
                            0
                        )
                        item.materialName = `小计： ${count}`

                        item.uuid = getUuid()
                        item.type = this.basicForm.leaseType

                        item.materialClassName = item.topClassName
                        item.children.forEach(v=>{
                            v.uuid = getUuid()
                            v.parentId = item.uuid
                        })
                    })

                    this.detailedTableData = res
                }

                this.collectCount()
                this.onTaxRate()
            })
        },
        //更新基本信息
        updateBaseInfo () {
            return new Promise((resolve, reject)=>{
                this.$refs.ruleForm.validate(valid => {
                    if (valid) {
                        otherRequest.turnoverInternalLeaseTransferChangedUpdate(this.basicForm).then(()=>{
                            this.getBasicInfo() //更新基本信息
                            resolve()
                        }).catch(err=>{
                            this.setError('baseInfo')
                            reject(err)
                        })
                    }
                    else {
                        this.setError('baseInfo')
                        this.scorllError()
                        return false
                    }
                })
            })
        },
        //更新计划明细
        updateBudgetDtl () {
            return new Promise((resolve, reject)=>{
                this.verifyTable().then(()=>{
                    otherRequest.turnoverInternalLeaseTransferChangedUpdateDtl(this.detailedTableData).then(()=>{
                        this.getdtlList() //更新明细
                        resolve()
                    }).catch(err=>{
                        this.setError('detailed')
                        this.scorllError()
                        reject(err)
                    })
                }).catch(err=>{
                    this.setError('detailed')
                    this.scorllError()

                    reject(err)
                })

            })
        },
        async exas (arg) {
            const requestFn = () => {
                return []
            }
            exas(arg, this, requestFn)
        },
        //保存全部数据
        saveAll () {
            const requestFn = ()=>{
                return [
                    this.updateBaseInfo(),
                    this.updateBudgetDtl(),

                ]
            }
            saveAll(this, requestFn)
        },
        submitCommit () {
            const requestFn = ()=>{
                return [
                    this.updateBaseInfo(),
                    this.updateBudgetDtl(),
                ]
            }
            submitCommit(this, requestFn)
        },

        selectIdle () {
            setInternalLeaseselectIdleRegistration(this.detailedTableData, this.billId).then(res=>{
                this.detailedTableData = res
            })
        },
        //明细金额向上汇总到基础表单 变更计划金额
        collectCount () {
            this.basicForm.rmbNotTaxprice = 0

            this.detailedTableData.forEach(v => {
                v.children.forEach(item => {
                    if (item.oldState != -1) {
                        this.basicForm.rmbNotTaxprice += Number(item.amountChanged)
                    }
                })
                const count = v.children.reduce(
                    (prev, c) => (prev += Number(c.amountChanged) || 0),
                    0
                )
                v.materialName = `小计： ${count}`
            })
        },
        //税率失去焦点的时候 计算 税额 = 不含税计划金额（元）*税率%
        onTaxRate (curInputValue) {
            // if (
            //     this.basicForm.rmbNotTaxprice != 0 &&
            //     this.basicForm.taxRate != 0
            // ) {
            //     this.basicForm.taxAmount =
            //         (this.basicForm.rmbNotTaxprice *
            //             this.basicForm.taxRate) /
            //         100
            // }

            if (this.basicForm.amountOfMoney != 0 && this.basicForm.taxRate != 0) {
                if(curInputValue !== 'taxAmount') {
                    if(this.basicForm.taxRate) {
                        // 税额
                        this.basicForm.taxAmount =
                Number((this.basicForm.rmbNotTaxprice * this.basicForm.taxRate) / 100).toFixed(2)
                    }
                }
                // 计划金额
                this.basicForm.changedTotalMoney =
                  (Number(this.basicForm.taxAmount) + Number(this.basicForm.rmbNotTaxprice)).toFixed(2)

            }

        },
        //判断当前状态是否已修改
        curStateChange (row) {

            this.curRow = row
            // row.amount =  row.demandQuantity * row.purchasePrice

            if(row.oldState != -1 ) {
                if (row.dtlId) {
                    if (row.oldState === 2 || row.oldState === 0 || row.oldState === null) {

                        this.curRow.oldState = 2
                    }else if(row.oldState === 1) {
                        this.curRow.oldState = 1

                    }
                    this.curRow.changeType = 2
                }
                this.numYuan(row)
            }
        },

        numYuan (row) {
            // 计算：租赁单价*数量*时间+进场费用
            if(row.quantityChanged && row.priceChanged && row.useTimeChanged && row.costChanged) {
                row.amountChanged = (Number( row.quantityChanged) * Number(row.priceChanged) * Number(row.useTimeChanged) + Number(row.costChanged)).toFixed(2)

                this.collectCount()
                this.onTaxRate()
            }

        },
        //计划明细非空验证
        verifyTable () {
            return new Promise((resolve, reject)=>{

                this.errorMsg = []

                this.detailedTableData.forEach(v => {
                    v.children.forEach((item, index) => {
                        if (item.changeType !== -1) {

                            if (item.quantityChanged == '' || item.quantityChanged == null) {
                                let str = `请填写第 ${index + 1} 行的变更租赁数量`
                                this.errorMsg.push(str)
                            }
                            if (item.priceChanged == '' || item.priceChanged == null) {
                                let str = `请填写第 ${index + 1} 行的变更租赁单价（元）`
                                this.errorMsg.push(str)
                            }
                            if (item.degreeChanged == '' || item.degreeChanged == null) {
                                let str = `请填写第 ${index + 1} 行的变更单价`
                                this.errorMsg.push(str)
                            }
                            if (item.timeUnitChanged == '' || item.timeUnitChanged == null) {
                                let str = `请填写第 ${index + 1} 行的变更计时单位`
                                this.errorMsg.push(str)
                            }
                            if (item.useTimeChanged == '' || item.useTimeChanged == null) {
                                let str = `请填写第 ${index + 1} 行的变更预计使用时间`
                                this.errorMsg.push(str)
                            }
                            if (item.costChanged == '' || item.costChanged == null) {
                                let str = `请填写第 ${index + 1} 行的变更预计进场费用`
                                this.errorMsg.push(str)
                            }

                        }
                    })
                })

                if (this.errorMsg.length > 0) {
                    this.isErrorMsg = true
                    reject()

                } else {
                    this.isErrorMsg = false
                    resolve()

                }

            })

        },
        tableRowClass ({ row }) {
            if(row.oldState == -1) {
                if(row.internalLeaseTransferDtlId) { //判断是否原单
                    return 'red'
                }else{
                    return  'row-hide'
                }
            }else if(row.oldState == 1) {
                return 'green'
            }else if(row.oldState == 2) {
                return 'yellow'
            }
            return ''
        },
        deleteEle (row) {
            row.changeType = -1
            row.oldState = -1
            this.collectCount()
        },
        getBasicInfo () {
            this.$Ajax
                .httpGet({
                    url: '/turnover/internalLeaseTransferChanged/findById',
                    params: {
                        billId: this.billId
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(res => {
                    res.isShare == 1 ? res.isShare = true : res.isShare = false

                    let arr = this.basicForm.dtls
                    for (let key in res) {
                        this.basicForm[key] = res[key]
                        this.basicForm.dtls = arr
                    }
                })
        },

        onSave () {
            this.$Ajax
                .httpPost({
                    url: '/turnover/internalLeaseTransferChanged/update',
                    params: this.basicForm
                })
                .then(() => {

                    this.clientPop('suc', '修改成功', this.getBasicInfo)
                })
        },
        //点击删除
        clickDel () {
            this.clientPop(
                'info',
                '确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。',
                this.delData
            )
        },
        delData () {
            showLoading()
            this.$Ajax
                .httpGet({
                    url: '/turnover/internalLeaseTransferChanged/delete',
                    params: { billId: this.billId },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(() => {
                    hideLoading()
                    this.clientPop('suc', '删除成功', this.handleClose)
                })
        },

        handleClose () {
            this.$router.push('/revolveInternalLeaseTransferList')

        },
        //设置错误标签
        setError (name) {
            if(!this.errorList.find(x=>x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item=>{
                let index = this.tabArr.findIndex(x=>x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },

    }
}
</script>

<style lang="scss" scoped>
.e-table {
    min-height: auto;
    background: #fff;
}
.upload {
    margin: 20px auto;
    display: flex;
    justify-content: center;
    text-align: center;
}

.upload-demo {
    display: flex;
    justify-content: center;
    align-items: center;
}

::v-deep.el-input--suffix .el-input__inner {
    padding-right: 5px;
}
::v-deep.el-table .cell {
    text-align: center;
}
#iconEdit:hover {
  color: blue;
}

.like {
  color: rgb(46, 97, 215);
  font-size: 17px;
  line-height: 30px;
  cursor: pointer;
}
</style>
